﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BlazorAdmin.Web.Shared.Components;
using BlazorAdmin.Web.Shared.Extensions;
using BlazorAdmin.Web.Shared.Services;
using BlazorAdmin.Web.Shared.Validators;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System.Diagnostics.CodeAnalysis;

namespace BlazorAdmin.Web.Shared.Pages.Admin;

/// <summary>
/// 
/// </summary>
public partial class Users
{
    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }

    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }

    [Inject]
    [NotNull]
    private IGroup? GroupService { get; set; }

    [Inject]
    [NotNull]
    private IRole? RoleService { get; set; }

    [Inject]
    [NotNull]
    private IUser? UserService { get; set; }

    [Inject]
    private IOrganize? OrganizeService { get; set; }

    [Inject]
    private MessageService? MsgService { get; set; }

    [Inject]
    private BootstrapAppContext? AppContext { get; set; }

    private static bool GetDisabled(int id) => id > 0;

    private List<IValidator> UserRules { get; } = new List<IValidator>();

    private DialogOption? Option { get; set; }

    private List<TreeViewItem<Organize>>? OrganizeTree { get; set; }

    private string? SelectedOrgCode { get; set; }

    private AdminTable<User>? Table;

    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        base.OnInitialized();

        UserRules.Add(new UserNameValidator(UserService));
        OrganizeTree = await OrganizeService?.GetOrganizeTree(AppContext?.LoginName, true);
    }

    /// <summary>
    /// 分配角色
    /// </summary>
    private async Task OnAssignmentRoles(User user)
    {
        List<SelectedItem> groups = RoleService.GetAll().ToSelectedItemList();
        List<int> values = RoleService.GetRolesByUserId(user.ID);

        await DialogService.ShowAssignmentDialog($"分配角色 - 当前用户: {user}", groups, values, () =>
        {
            IEnumerable<int> ids = from u in groups where u.Active select int.Parse(u.Value);
            bool result = RoleService.SaveRolesByUserId(user.ID, ids);
            return Task.FromResult(result);
        }, ToastService);
    }

    /// <summary>
    /// 分配组织
    /// </summary>
    private async Task OnAssignmentOrganize(User user)
    {
        Option = new DialogOption()
        {
            Title = "选择设备组",
            IsScrolling = true,
            Size = Size.Medium,
            BodyTemplate = BootstrapDynamicComponent.CreateComponent<TreeView<Organize>>(new Dictionary<string, object?>
            {
                [nameof(TreeView<Organize>.ShowIcon)] = true,
                [nameof(TreeView<Organize>.ShowSkeleton)] = true,
                [nameof(TreeView<Organize>.Items)] = OrganizeTree,
                [nameof(TreeView<Organize>.OnTreeItemClick)] = async (TreeViewItem<Organize> item) => {
                    if (item.Value.OrgCode.ToLower() == "default") // 选择未分组
                        SelectedOrgCode = item.Value.ParentOrgCode;
                    else
                        SelectedOrgCode = item.Value.OrgCode;
                }
            }).Render(),
            FooterTemplate = BootstrapDynamicComponent.CreateComponent<Button>(new Dictionary<string, object?>
            {
                [nameof(Button.Color)] = Color.Primary,
                [nameof(Button.Text)] = "确认",
                [nameof(Button.Icon)] = "fa-solid fa-fw fa-check",
                [nameof(Button.OnClick)] = EventCallback.Factory.Create<MouseEventArgs>(this, async () =>
                {
                    if (string.IsNullOrEmpty(SelectedOrgCode))
                    {
                        MsgService?.Show(new() { Content = "请选择组织" });
                        return;
                    }

                    UserService.SaveUserOrg(user.UserName, SelectedOrgCode);

                    Table.QueryAsync();
                    await Option.CloseDialogAsync();

                    await ToastService.Success("分配操作", "操作成功！");
                })
            }).Render()
        };

        await DialogService.Show(Option);
    }

    /// <summary>
    /// 分配用户组
    /// </summary>
    private async Task OnAssignmentGroups(User user)
    {
        List<SelectedItem> groups = GroupService.GetAll().ToSelectedItemList();
        List<int> values = GroupService.GetGroupsByUserId(user.ID);

        await DialogService.ShowAssignmentDialog($"分配部门 - 当前用户: {user}", groups, values, () =>
        {
            IEnumerable<int> ids = from u in groups where u.Active select int.Parse(u.Value);
            bool result = GroupService.SaveGroupsByUserId(user.ID, ids);
            return Task.FromResult(result);
        }, ToastService);
    }

    private Task<bool> OnSaveAsync(User user, ItemChangedType itemChangedType)
    {
        return Task.FromResult(UserService.SaveUser(user.UserName, user.NewPassword, user.DisplayName));
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    private Task<QueryData<User>> OnQueryAsync(QueryPageOptions options)
    {
        return UserService?.Query(new AppQueryOption<string>(options));
    }
}
